<?php
require_once '../../classes/includeAll_Layer2.php';


if(!isset($_POST["action"]))
{
  echo json_encode (array("success"=>"false","message"=>"Ungültige Anweisung"));
  exit();
}
require '../../resources/getConnection.php';
$message = "";
$success = "";

switch($_POST["action"])
{
  case "delete":
    if(!isset($_POST["supplier"])||!is_numeric($_POST["supplier"]))
    {
      $success = "false";
      $message ="Ungültige Anweisung";
    }
    else
    {
      $dependentDevices = array();
      $devicesClass = new Devices($connection);
      $devices = $devicesClass->getAllDevices();
      foreach($devices as $device)
      {
        if($device->SupplierID==$_POST["supplier"])
          array_push ($dependentDevices, $device->Name);
      }
      if(count($dependentDevices)==0)
      {
        $supplierClass = new Suppliers($connection);
        $supplierClass->DeleteSupplier($_POST["supplier"]);
        $success = "true";
      }
      else
      {
        $success = "false";
        $message="Folgende Geräte verwenden diesen Lieferant:\n";
        foreach ($dependentDevices as $name) {
          $message.=" -".$name."\n";
        }
      }
    }
    break;
  case "add":
    if(!isset($_POST["name"]))
    {
      $success = "false";
      $message ="Ungültige Anweisung";
    }
    else
    {
      $name = $_POST["name"];
      $contactService = "";
      $contactSaleOffice = "";
      $note = "";
      if(isset($_POST["contactService"]))
      {
        $contactService = $_POST["contactService"];        
      }
      if(isset($_POST["contactSalesOffice"]))
      {
        $contactSaleOffice = $_POST["contactSalesOffice"];
      }
      if(isset($_POST["note"]))
      {
        $note = $_POST["note"];
      }
      $supplierClass = new Suppliers($connection);
      $supplierClass->name = $name;
      $supplierClass->contactService=$contactService;
      $supplierClass->contactSalesOffice=$contactSaleOffice;
      $supplierClass->note = $note;
      $supplierClass->ExistsOrCreate();
      if($supplierClass->inserted)
      {
      $message = '<tr>'
              . '<td>'.$name.'</td>'
              . '<td>'.$contactService.'</td>'
              . '<td>'.$contactSaleOffice.'</td>'
              . '<td>'.$note.'</td>'
              . '<td supplier="'.$supplierClass->ID.'"><img src="../design/pictures/delete.png" width="20" alt="X"/></td>'
              . '</tr>';
      $success = "true";
      }
      else
      {
        $success = "false";
        $message = "Lieferant mit gleichem Namen bereits vorhanden";
      }
    }
    break;
  
  default:
    $success = "false";
    $message ="Ungültige Anweisung";
    break;
}
echo json_encode (array("success"=>$success,"message"=>$message));
$connection->disconnectDB();